package com.example.goodtrash.search;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.goodtrash.R;
import com.example.goodtrash.db.GoodTrashDB;
import com.example.goodtrash.model.Result;
import com.example.goodtrash.model.Trash;
import com.example.goodtrash.util.HttpUtil;
import com.example.goodtrash.util.Utility;
import com.google.android.material.appbar.MaterialToolbar;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class textSearch extends AppCompatActivity {
    private List<Trash> dataList=new ArrayList<>();
    private TrashAdapter adapter;
    private EditText etGoods;
    private ImageView ivClear;
    private RecyclerView rvResult;
    private ProgressDialog progressDialog;
    private MaterialToolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_search);
        etGoods=findViewById(R.id.et_goods);
        ivClear=findViewById(R.id.iv_clear);
        rvResult=findViewById(R.id.rv_result);
        toolbar=findViewById(R.id.toolbar);
        adapter=new TrashAdapter(dataList,textSearch.this,textSearch.this);
        rvResult.setLayoutManager(new LinearLayoutManager(this));
        rvResult.setAdapter(adapter);
        if (getIntent().getStringExtra("hotSearch")!=null){
            showLoadingDialog();
            controlInputMethod();
            queryResult(getIntent().getStringExtra("hotSearch"));
        }

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        etGoods.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
               if(charSequence.toString().length()<1){
                   ivClear.setVisibility(View.INVISIBLE);
               }else {
                   ivClear.setVisibility(View.VISIBLE);
               }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        etGoods.setOnEditorActionListener((textView, i, keyEvent) -> {
            if(i== EditorInfo.IME_ACTION_SEARCH){
                String word=etGoods.getText().toString().trim();
                if(word.isEmpty()){
                    Toast.makeText(textSearch.this,"请输入物品名",Toast.LENGTH_SHORT).show();
                }else {
                    showLoadingDialog();
                    controlInputMethod();
                    queryResult(word);
                }
                return true;
            }
            return false;
        });

        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                controlInputMethod();
                etGoods.setText("");
            }
        });
    }


    private void controlInputMethod(){
        InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
    }


    private void showLoadingDialog(){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(textSearch.this);
            progressDialog.setMessage("正在加载.....");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }


    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    private void queryResult(String text){
        HttpUtil.sendOkHttpRequest(text, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
             Toast.makeText(textSearch.this,"搜索失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                 String responseText=response.body().string();
                 Result result=Utility.handleTrashResponse(responseText);
                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         if(result!=null&&"success".equals(result.getMessage())){

                             closeProgressDialog();
                             GoodTrashDB db=GoodTrashDB.getInstance(textSearch.this);
                             dataList.clear();
                             List<Trash> trashList=result.getTrashList();
                             for(Trash trash: trashList) {
                                 db.saveHistory(trash);
                                 dataList.add(trash);
                             }
                             adapter.notifyDataSetChanged();

                         } else if("No match result".equals(result.getMessage())){
                             closeProgressDialog();
                             Toast.makeText(textSearch.this,"搜索到知识盲区啦",Toast.LENGTH_SHORT).show();
                         } else if ("param error".equals(result.getMessage())){
                             closeProgressDialog();
                             Toast.makeText(textSearch.this,"请输入简体中文",Toast.LENGTH_SHORT).show();
                         }
                     }
                 });
            }
        });
    }


    private void setBarColor(){
        Window window=getWindow();
        window.setStatusBarColor(getResources().getColor(R.color.white));

    }


}